package com.tpp.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Package: com.tpp.config
 * @ClassName: ElasticSearchConfig
 * @Author: myh
 * @CreateTime: 2021/9/11 15:44
 * @Description:
 */

@Configuration
public class ElasticSearchConfig {

    @Value("${springcloud-es.elasticsearch.hostlist}")
    private String hostlist;
//    这个表示读取配置文件中的地址

    @Bean
//    bean注解  表示交给spring去管理
    public RestHighLevelClient restHighLevelClient(){
//        1、解析hostlist配置信息，先用，进行分割，
        String[] split = hostlist.split(",");

//        2、创建HttpHost数组、其中存放es主机和端口号的配置信息
        HttpHost[] httpHosts = new HttpHost[split.length];

//        3、遍历httphosts，
        for (int i=0;i<split.length;i++){
            String item = split[i];
            httpHosts[i] = new HttpHost(item.split(":")[0],Integer.parseInt(item.split(":")[1]),"http");
        }

//        4、创建RestHignLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHosts));

    }

}
